<?php

namespace admin\modules\equipment_info\models;

use common\models\db\EquipmentOperateLog;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * EquipmentOperateLogSearch represents the model behind the search form about `admin\modules\equipment_info\models\EquipmentOperateLog`.
 */
class EquipmentOperateLogSearch extends EquipmentOperateLog
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'equipment_id', 'status', 'for_equipment_user', 'operate_type'], 'integer'],
            [['action_route', 'req_data', 'resp_data', 'created_at'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = EquipmentOperateLog::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'equipment_id' => $this->equipment_id,
//            'created_at' => $this->created_at,
            'status' => $this->status,
            'for_equipment_user' => $this->for_equipment_user,
            'operate_type' => $this->operate_type,
        ]);

        $query->andFilterWhere(['like', 'action_route', $this->action_route])
            ->andFilterWhere(['like', 'req_data', $this->req_data])
            ->andFilterWhere(['like', 'resp_data', $this->resp_data]);

        if ( ! is_null($this->created_at) && strpos($this->created_at, ' - ') !== false ) {
            list($start_date, $end_date) = explode(' - ', $this->created_at);
            $query->andFilterWhere(['between', 'created_at', strtotime($start_date), strtotime($end_date.' 23:59:59')]);
        }

        return $dataProvider;
    }
}
